<template>
  <Modal
    v-model="showImportApiExcelModal"
    title="导入接口|用例"
    fullscreen
    :mask-closable="false"
    :closable="false"
    @on-cancel="handleImportCancel"
  >
    <div style="display: flex; justify-content: flex-start">
      <Form
        inline
        :label-width="100"
        :model="uploadApiData"
        :rules="uploadApiDataValidate"
        ref="uploadApiData"
      >
        <FormItem label="所属项目" prop="project">
          <Select
            v-model="uploadApiData.project"
            filterable
            style="width: 300px"
          >
            <Option
              v-for="item in projects"
              :value="item.id"
              :key="item.id"
              :label="item.name"
            />
          </Select>
        </FormItem>
        <FormItem label="创建场景">
          <i-switch
            true-color="#13ce66"
            false-color="#ff4949"
            size="large"
            v-model="uploadApiData.create_testsuite"
            @on-change="$refs['uploadApiData'].validate()"
          >
            <span slot="open">Yes</span>
            <span slot="close">No</span>
          </i-switch>
        </FormItem>
        <FormItem label="场景名称" prop="testsuite_name">
          <Input
            style="width: 300px"
            :disabled="!uploadApiData.create_testsuite"
            v-model="uploadApiData.testsuite_name"
          />
        </FormItem>
        <FormItem :label-width="0">
          <Button
            size="small"
            type="text"
            icon="md-download"
            style="color: #2d8cf0"
            @click="downloadApiTemplate"
          >
            下载模板
          </Button>
        </FormItem>
        <FormItem :label-width="0">
          <Upload
            :before-upload="beforeUploadApiFile"
            action="#"
            accept=".xls,.xlsx"
          >
            <Button
              size="small"
              type="text"
              style="color: #2d8cf0"
              icon="md-cloud-upload"
            >
              文件上传
            </Button>
          </Upload>
        </FormItem>
      </Form>
    </div>
    <div class="file-div">
      <div v-if="file !== null">
        {{ file.name }}
        <Button
          size="small"
          type="text"
          style="color: #ed4014"
          @click="removeFile"
        >
          删除
        </Button>
      </div>
    </div>
    <div class="status-div">
      <span class="status-div-item">
        <Icon size="24" :color="statusColor['PASS']" type="ios-leaf" />通过
      </span>
      <span class="status-div-item">
        <Icon size="24" :color="statusColor['FAIL']" type="ios-leaf" />失败
      </span>
    </div>
    <Table
      :columns="apiColumns"
      :data="uploadApiData.api"
      border
      size="small"
      style="margin-top: 10px"
      :span-method="handleSpan"
      :tooltip-max-width="500"
    >
      <template slot-scope="{ row }" slot="status">
        <Icon
          size="24"
          :color="statusColor[row.status]"
          type="ios-leaf"
          v-show="row.status"
        />
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button
          size="small"
          type="text"
          style="color: #ed4014"
          @click="removeApi(row, index)"
          >移除</Button
        >
      </template>
    </Table>
    <div slot="footer">
      <Button type="default" @click="handleImportCancel">取消</Button>
      <Button
        type="primary"
        ghost
        @click="handleDebugSubmit"
        :disabled="!(uploadApiData.project && uploadApiData.api.length > 0)"
        :loading="debugging"
        >调试</Button
      >
      <Button
        type="primary"
        @click="handleImportSubmit('uploadApiData')"
        :disabled="!(uploadApiData.project && uploadApiData.api.length > 0)"
        >导入</Button
      >
    </div>
  </Modal>
</template>

<script>
import {
  downloadApiTemplate,
  uploadApiFile,
  debugApi,
  batchCreateApiAndTestcase,
} from "@/api/HttpAutoTestService/api";
import { getProjectNames } from "@/api/HttpAutoTestService/project";

export default {
  name: "api-excel-import",
  props: {
    importApiExcel: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    showImportApiExcelModal: {
      get() {
        return this.importApiExcel;
      },
      set(val) {
        this.$emit("update:importApiExcel", val);
      },
    },
  },
  mounted() {
    // 获取项目
    getProjectNames()
      .then((res) => {
        this.projects = res.data;
      })
      .catch((err) => {
        this.$Modal.error({
          title: "系统异常，请联系管理员……",
          content: JSON.stringify(err),
          closable: true,
        });
      });
  },
  data() {
    const validateTestsuiteName = (rule, value, callback) => {
      if (
        this.uploadApiData.create_testsuite &&
        (this.uploadApiData.testsuite_name == "" ||
          this.uploadApiData.testsuite_name == undefined)
      ) {
        callback(new Error("请输入场景名称"));
      } else {
        callback();
      }
    };
    return {
      statusColor: {
        PASS: "#19be6b",
        FAIL: "#ed4014",
      },
      apiColumns: [
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left",
        },
        {
          title: "接口名称（必填）",
          key: "name",
          width: 350,
          tooltip: true,
          fixed: "left",
        },
        {
          title: "类型",
          key: "type",
          align: "center",
          width: 125,
        },
        {
          title: "请求URL|扩展方法（必填）",
          key: "url_or_ext_method",
          width: 350,
          tooltip: true,
        },
        {
          title: "请求方法",
          key: "method",
          align: "center",
          width: 100,
        },
        {
          title: "Headers参数（选填）",
          key: "headers",
          width: 350,
          align: "center",
          tooltip: true,
        },
        {
          title: "Body参数类型（选填）",
          key: "request_data_type",
          width: 120,
          align: "center",
        },
        {
          title: "Body参数",
          key: "request_data",
          width: 350,
          align: "center",
          tooltip: true,
        },
        {
          title: "创建用例（选填）",
          key: "create_testcase",
          align: "center",
          width: 100,
        },
        {
          title: "用例期望结果（选填）",
          key: "expect_result",
          width: 350,
          align: "center",
          tooltip: true,
        },
        {
          title: "备注",
          key: "remark",
          minWidth: 350,
          tooltip: true,
        },
        {
          title: "调试结果",
          align: "center",
          children: [
            {
              title: "响应状态码",
              key: "status_code",
              width: 100,
              align: "center",
            },
            {
              title: "响应结果",
              key: "response_data",
              minWidth: 350,
              align: "center",
              tooltip: true,
            },
            {
              title: "输出变量结果",
              key: "output_result",
              minWidth: 350,
              align: "center",
              tooltip: true,
            },
            {
              title: "失败原因",
              key: "failure_reason",
              minWidth: 350,
              align: "center",
              tooltip: true,
            },
            {
              title: "测试结果",
              slot: "status",
              align: "center",
              width: 85,
            },
          ],
        },
        {
          title: "操作",
          slot: "action",
          width: 80,
          align: "center",
          fixed: "right",
        },
      ],
      file: null,
      projects: [],
      uploadApiData: {
        project: "",
        create_testsuite: false,
        testsuite_name: "",
        api: [],
      },
      uploadApiDataValidate: {
        project: [{ required: true, message: "请选择项目", trigger: "change" }],
        testsuite_name: [{ validator: validateTestsuiteName, trigger: "blur" }],
      },
      debugging: false,
    };
  },
  methods: {
    removeFile() {
      this.file = null;
      this.uploadApiData.api = [];
    },
    removeApi(row, index) {
      this.uploadApiData.api.splice(index, 1);
      if (this.uploadApiData.api.length == 0) {
        this.removeFile();
      }
    },
    downloadApiTemplate() {
      downloadApiTemplate().then((res) => {
        if (res.status === 200) {
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          const blobUrl = window.URL.createObjectURL(blob);
          const elementLink = document.createElement("a");
          elementLink.download = "批量创建接口模板.xlsx";
          elementLink.style.display = "none";
          elementLink.href = blobUrl;
          // 触发点击
          document.body.appendChild(elementLink);
          elementLink.click();
          // 然后移除
          document.body.removeChild(elementLink);
        }
      });
    },
    beforeUploadApiFile(file) {
      this.file = file;
      let formData = new FormData();
      formData.append("file", this.file);
      uploadApiFile(formData).then((res) => {
        this.uploadApiData.api = res.data;
      });
      return false;
    },
    handleDebugSubmit() {
      let data = {
        project: this.uploadApiData.project,
        api: this.uploadApiData.api,
      };
      this.debugging = true;
      debugApi(data).then((res) => {
        this.uploadApiData.api = res.data;
        this.debugging = false;
      });
    },
    handleImportSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          batchCreateApiAndTestcase(this.uploadApiData)
            .then((res) => {
              if (res.status === 200) {
                let data = res.data;
                let create_testsuite_msg = this.uploadApiData.create_testsuite
                  ? `创建新场景：${data.new_testsuite} 个，新场景名称：${data.new_testsuite_name}<br/>`
                  : "";
                let content = `
                  创建新接口：${data.new_api} 个，已存在接口：${data.exist_api} 个<br/>
                  ${create_testsuite_msg}
                  创建新用例：${data.new_testcase} 个
                `;
                this.$Modal.info({
                  title: "导入 接口|用例 完成",
                  content: content,
                  closable: true,
                  width: 500,
                });
                this.handleImportCancel();
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },
    handleImportCancel() {
      this.showImportApiExcelModal = false;
      this.uploadApiData = {
        project: "",
        create_testsuite: false,
        testsuite_name: "",
        api: [],
      };
      this.removeFile();
      this.$emit("initApiTable");
      this.$refs["uploadApiData"].resetFields();
    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if (row.type === "EXT_METHOD") {
        if (columnIndex === 3) {
          return {
            rowspan: 1,
            colspan: 5,
          };
        } else if (columnIndex >= 3 && columnIndex <= 7) {
          return {
            rowspan: 1,
            colspan: 0,
          };
        } else {
          return {
            rowspan: 1,
            colspan: 1,
          };
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.file-div {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 10px;
}
.status-div {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  .status-div-item {
    margin-left: 10px;
  }
}
</style>
